package cn.itsource.aop;

import cn.itsource.annotation.CaoYuPiCacheAdd;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * <p>切面类：处理分布式缓存添加的</p>
 *
 * @author 波波老师(微信 ： javabobo0513)
 * @date 2022/11/16-18:16
 */
@Aspect
@Component
public class MyCacheAop {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 1、通过注解
     * 2、通过路径
     */

    //定义一个切点
    @Pointcut(value="@annotation(caoYuPiCacheAdd)")
    public void cutpoint(CaoYuPiCacheAdd caoYuPiCacheAdd){
    }
    /**
     * 环绕通知
     * 前置通知
     * 后置通知
     * 异常通知
     */
    /**
     * 环绕通知
     */
    @Around("cutpoint(caoYuPiCacheAdd)")
    public Object around(ProceedingJoinPoint joinPoint, CaoYuPiCacheAdd caoYuPiCacheAdd) throws Throwable {
        //拼接key
        String redisKey = caoYuPiCacheAdd.cacheNames() + ":" + caoYuPiCacheAdd.key();
        //获取缓存时间
        int time = caoYuPiCacheAdd.time();
        //查询Redis看是否有值
        Object obj = redisTemplate.opsForValue().get(redisKey);
        if(obj != null){
            //如果有值，直接返回
            return obj;
        }
        //执行目标方法
        Object proceed = joinPoint.proceed();
        //将缓存存入Redis
        if(time == -1){
            redisTemplate.opsForValue().set(redisKey, proceed);
        }else{
            redisTemplate.opsForValue().set(redisKey, proceed, time, TimeUnit.SECONDS);
        }
        return proceed;
    }
}